import 'dart:async';

import 'package:flutter/material.dart';
import 'package:audioplayers/audioplayers.dart';
import 'package:get/get.dart';
import 'package:gif/gif.dart';

import '../common/events.dart';
import '../controllers/chat_controller.dart';

class AudioMessageView extends StatefulWidget {
  final String audioUrl;
  final bool isMe;

  const AudioMessageView({super.key, required this.isMe, required this.audioUrl});

  @override
  State<AudioMessageView> createState() => _AudioMessageViewState();
}

class _AudioMessageViewState extends State<AudioMessageView> with TickerProviderStateMixin {
  late final GifController _gifController;
  final _player = AudioPlayer();
  var _audioDuration = 0;
  var _isPlaying = false;
  var _isAutoPlay = false;
  StreamSubscription? _playerCompleteSubscription;
  StreamSubscription? _autoPlayAudioSubscription;

  @override
  void initState() {
    super.initState();

    _getAudioDuration();

    _gifController = GifController(vsync: this);

    _playerCompleteSubscription = _player.onPlayerComplete.listen((event) {
      if (mounted) {
        _gifController.stop();
        if (_isAutoPlay) {
          _isAutoPlay = false;
          _playNextAudio();
        }
        setState(() {
          _isPlaying = false;
        });
      }
    });

    _autoPlayAudioSubscription = eventBus.on<PlayAudioEvent>().listen((event) {
      if (event.audioUrl == widget.audioUrl) {
        if (!_isPlaying) {
          _isAutoPlay = event.autoPlay;
          _playAudio();
        }
      } else {
        _stopAudio();
      }
    });
  }

  @override
  void dispose() {
    _autoPlayAudioSubscription?.cancel();
    _playerCompleteSubscription?.cancel();
    _player.dispose();
    _gifController.dispose();
    super.dispose();
  }

  _getAudioDuration() async {
    try {
      final audioUrl = widget.audioUrl.trim();
      await _player.setSource(UrlSource(audioUrl));
      await _player.setReleaseMode(ReleaseMode.stop);
      final duration = await _player.getDuration();
      if (duration != null) {
        setState(() {
          _audioDuration = duration.inSeconds;
        });
      }
    } catch (e) {
      print("【${widget.audioUrl.trim()}】Error loading audio: $e");
    }
  }

  String _formatTime(int seconds) {
    if (seconds < 60) {
      return "$seconds''";
    } else {
      int minutes = seconds ~/ 60;
      int remainingSeconds = seconds % 60;

      return remainingSeconds > 0 ? "$minutes'$remainingSeconds''" : "$minutes'";
    }
  }

  _playNextAudio() {
    final controller = Get.find<ChatController>(tag: Get.arguments['pipeId']);
    controller.autoPlayAudio();
  }

  _clearAutoPlayAudioQueue() {
    final controller = Get.find<ChatController>(tag: Get.arguments['pipeId']);
    controller.clearAutoPlayAudioQueue();
  }

  Future<void> _playAudio() async {
    _gifController.repeat();
    setState(() {
      _isPlaying = true;
    });
    await _player.seek(Duration.zero);
    _player.resume();

    eventBus.fire(PlayAudioEvent(audioUrl: widget.audioUrl, autoPlay: false));
  }

  Future<void> _stopAudio() async {
    _clearAutoPlayAudioQueue();
    _gifController.stop();
    _player.stop();
    setState(() {
      _isPlaying = false;
    });
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      behavior: HitTestBehavior.translucent,
      child: Container(
        decoration: BoxDecoration(
          color: widget.isMe ? Color(0xFF8CFE86) : Color(0xFF3F4B60),
          borderRadius: BorderRadius.circular(6),
        ),
        padding: EdgeInsets.only(left: 2, top: 2, right: 10, bottom: 2),
        margin: EdgeInsets.only(top: 10),
        child: Row(
          mainAxisSize: MainAxisSize.min,
          children: [
            Icon(
              _isPlaying ? Icons.pause : Icons.play_arrow,
              size: 22,
              color: widget.isMe ? Colors.black : Colors.white,
            ),
            SizedBox(
              width: 4,
            ),
            Gif(
              controller: _gifController,
              image: widget.isMe ? const AssetImage('assets/images/img_audio_play_animation_light.webp') : const AssetImage('assets/images/img_audio_play_animation_dark.webp'),
              width: 32,
              fit: BoxFit.cover,
            ),
            SizedBox(
              width: 8,
            ),
            if (_audioDuration > 0)
              Text(
                _formatTime(_audioDuration),
                style: TextStyle(color: widget.isMe ? Colors.black : Colors.white, fontSize: 14, fontFamily: 'dinpro', fontWeight: FontWeight.w600),
              )
          ],
        ),
      ),
      onTap: () async {
        if (_isPlaying) {
          await _stopAudio();
        } else {
          await _playAudio();
        }
      },
    );
  }
}
